<template>
  <div>
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      @search="onSearch"
      @input="onSuggest"
    >
      <template #left>
        <van-icon
          class="icon"
          name="arrow-left"
          @click="goBack"
        />
      </template>
      <template #action>
        <span
          class="search-btn"
          @click="onSearch"
        >
          搜索
        </span>
      </template>
    </van-search>

    <!-- 搜索建议列表 -->
    <van-loading
      v-if="searchRecordLoading"
      class="loading"
      color="#1989fa"
    />
    <van-list
      v-else-if="value.trim()&& !searchRecordLoading"
      :finished="true"
    >
      <van-cell
        v-for="item in fuzzySearchList"
        :key="item"
        @click="onSearch"
      >
        <van-icon name="search" />
        <span v-html="getHighlightHTML(item)" />
      </van-cell>
    </van-list>

    <!-- 历史记录 -->
    <van-list
      v-else
      :finished="true"
    >
      <van-cell v-if="searchRecord.length">
        <template #title>
          <span
            class="title"
          >
            历史记录
          </span>
        </template>
        <van-icon
          name="delete"
          size="18"
          @click="onSearchRecordRemove"
        />
      </van-cell>
      <van-cell
        v-for="(item, i) in searchRecord"
        :key="item"
        :title="item"
      >
        <van-icon
          name="cross"
          size="16"
          @click="onSearchRecordItemRemove(i)"
        />
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { uniq, debounce } from 'lodash';

export default {
  name: 'SearchPage',
  data() {
    return {
      value: '',
      searchRecordLoading: false,
      // 返显
      searchRecord: JSON.parse(localStorage.getItem('searchRecord')) || [],
    };
  },
  computed: {
    ...mapState('fuzzySearch', [
      'fuzzySearchList',
    ]),
  },
  methods: {
    ...mapActions('fuzzySearch', [
      'updateFuzzySearchList',
    ]),
    onSearch() {
      if (!this.value.trim()) {
        return;
      }
      localStorage.setItem('searchRecord', JSON.stringify(uniq([this.value].concat(this.searchRecord))));

      // 跳转页面
      this.$router.push({
        path: '/search',
        query: {
          q: this.value,
        }
      })
    },
    // 点击历史记录跳转页面
    // onSuggest(value) {
    //   if (!value.trim()) {
    //     return;
    //   }
    //   this.updateFuzzySearchList(value);
    // },
    // 防抖
    updateSuggestionListWithDebounce: debounce(async function (value) {
      await this.updateFuzzySearchList(value);
      this.searchRecordLoading = false;
    }, 2000),
    onSuggest (value) {
      if (!value.trim()) {
        return;
      }
      this.searchRecordLoading = true;
      this.updateSuggestionListWithDebounce(value);
    },
    getHighlightHTML(str) {
      // 'angular' >>> '<span class="highlight">a</span>ngular'
      return str.toLowerCase().replace(this.value, `<span class="highlight">${ this.value }</span>`);
    },
    // 删除搜索记录中的一项
    onSearchRecordItemRemove(idx) {
      // 用于显示
      this.searchRecord.splice(idx, 1);
      // 用于记录
      localStorage.setItem('searchRecord', JSON.stringify(this.searchRecord));
    },
    // 清空历史记录
    onSearchRecordRemove() {
      // 用于显示
      this.searchRecord = [];
      // 用于记录
      localStorage.removeItem('searchRecord');
    },
    // 返回之前的页面
    goBack() {
      this.$router.go(-1);
    },
  },
}
</script>

<style lang="less" scoped>
.icon {
  margin-right: 16px;
}
.search-btn {
  font-size: 14px;
  margin: 0 8px;
}
// 样式穿透
::v-deep .highlight {
  color: red;
}
.title {
  color: #999;
}
.loading {
  display: flex;
  justify-content: center;
  margin: 50px;
}
</style>
